package cn.sun.user.controller;

import cn.sun.basic.util.AjaxResult;
import cn.sun.basic.util.PageBean;
import cn.sun.user.domain.User;
import cn.sun.user.dto.UserDto;
import cn.sun.user.query.UserQuery;
import cn.sun.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户接口
 *    crud
 *    分页+高级
 */
@RestController //@Controller+@ResponseBody
@RequestMapping("/user")
@Api(value = "用户接口",description = "用户接口详细描述")
public class UserController {
    @Autowired
    private IUserService userService;

    //添加或修改-差异在于是否有id put
    @PutMapping
    @ApiOperation(value = "用户添加或修改",notes = "如果有id就是修改否则就是添加！")
    public AjaxResult addOrUpdate(@RequestBody User user){
        //通过id判断是添加或者修改
        try{
            if (user.getId()!=null){
                userService.update(user);
            }else {
                userService.save(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存失败！"+e.getMessage());
        }

    }

    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){

        try {
            userService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!"+e.getMessage());
        }
    }

    //获取一个 get
    @GetMapping("/{id}") //Get http://localhost:8080/deparment/1 deparment/2
    public User findById(@PathVariable("id") Long id){
        return userService.findById(id);
    }

    //获取所有 get
    @GetMapping ///user
    public List<User> findAll(){
        return userService.findAll();
    }

    //分页+高级查询 //post /user 传递对象都往@RequestBody
    @PostMapping
    public PageBean<User> findPage(@RequestBody UserQuery query){
        return userService.findPage(query);
    }

    @PatchMapping
    public AjaxResult batchdel(@RequestBody List<Long> ids){
        try {
            userService.batchdel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败");
        }
    }

    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统错误"+e.getMessage());
        }
    }
}
